package com.siecomzg.cmlinterface;

import android.bluetooth.BluetoothDevice;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Base64;

import com.siecomzg.bean.BankCardInfoBean;
import com.siecomzg.bean.IdentityInfoBean;
import com.siecomzg.bean.LoadLogBean;
import com.siecomzg.bean.TradeLogBean;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.constconfig.ErrorDefine;
import com.siecomzg.module.EMVParam;
import com.siecomzg.module.EmvOptions;
import com.siecomzg.tool.ByteTool;
import com.siecomzg.tool.FileUnits;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.tool.StringUtil;
import com.siecomzg.transport.ConnectStatusCallback;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.Distribution;
import com.siecomzg.transport.SiecomDevice;
import com.siro.touch.lib.drivers.api.SccbaTouchDriversApi;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//import LogUtil;

/**
 * Created on 2017/5/22.
 */

public class CmlInterface implements SccbaTouchDriversApi{

    private static Distribution distribution = new Distribution();


    private static String lastPwd = null;

    private String MasterKeyIndex = "01";
    public byte encryptType;
    private String WasterKeyIndex = "01";
    String[] ret = new String[2];
    private static boolean BtFlag = false;
    @Override
    public String[] SCCBA_Connect(BluetoothDevice device) {

        LogUtil.e("GJ","蓝牙是否连接"+BtFlag);
        if(BtFlag){
            ret[0] = "0";
            LogUtil.e("GJ","蓝牙已连接...");
            return ret;
        }
        final long messageId1 = System.currentTimeMillis();
        final ResultLock lock = LockMap.pick(messageId1);
        SiecomDevice.connectStatusChange(new ConnectStatusCallback() {
            @Override
            public void onConnectStart() {
                LogUtil.e("connectStatusChange", "onConnectStart");
            }

            @Override
            public void onConnected() {
                BtFlag = true;
                LogUtil.e("connectStatusChange", "onConnected");
                try {

                    ret[0] = "0";
//            setEncrypt();
                } catch (Exception e) {
                    e.printStackTrace();
                    ret[0] = "-1";
                    ret[1] = e.getMessage();

                } finally {

                }
                ResultLock lock = LockMap.pick(messageId1);

                if (lock != null) {

                    synchronized (lock) {

                        lock.notify();
                        lock.setMessage(0);

                    }

                }
            }

            @Override
            public void onDisConnect(Throwable e) {
                LogUtil.e("connectStatusChange", e.getMessage());
                BtFlag = false;

                ret[0] = "-1";
                ret[1] = "连接失败";
                ResultLock lock = LockMap.pick(messageId1);
                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(-1);
                        lock.notify();

                    }
                }

            }
        });



        SiecomDevice.startConnect(device, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {


            }

            @Override
            public void onSuccess(Bundle bundle) {

//                afterLink();
            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        }, false);

        ResultLock r = new ResultLock(messageId1);
        LockMap.store(messageId1, r);
        try {
            synchronized (r) {
                r.wait(3000 + 30000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId1);
        }


        return ret;
    }

    @Override
    public String[] SCCBA_Disconnect() {
        String[] ret = new String[2];
        distribution.stop();
        LogUtil.e("GJ","蓝牙断开连接...");
        ret[0] = "0";
        return ret;
    }

    @Override
    public String[] SCCBA_ReadPin(int iEncryType, final int iTimes, int iLength, String strVoice, int EndType, final String strTimeout) {

        final long messageId1 = System.currentTimeMillis();
        String length =  String.format("%02d", iLength);

        if(iEncryType == 1){
            encryptType = ConstDefine.KEY_NOENCRYPTION;
        }else{
            encryptType = ConstDefine.KEY_SM;
        }

        SiecomDevice.keySetEncryptMode(encryptType, EndType, -1, -1, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId1);

                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(-1);
                        lock.notify();

                    }
                }



            }

            @Override
            public void onSuccess(Bundle bundle) {


                ResultLock lock = LockMap.pick(messageId1);

                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(0);
                        lock.notify();

                    }
                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, 3000, false);

        ResultLock r = new ResultLock(messageId1);
        LockMap.store(messageId1, r);
        try {
            synchronized (r) {
                r.wait(3000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId1);
        }


        LogUtil.e("GJ","设置加密模式成功...");
        if(r.getMessage()!=null&&(int)r.getMessage()!=0){
            String[] ret = new String[2];
            ret[0] = "-1";
            ret[1] = "endType error";
            return  ret;
        }
        LogUtil.e("SCCBA_ReadPin",r.getMessage()+"--");

        int passVioce = 0;
        String bankCardNo = "0000000000000000";
        String[] ret = new String[2];
        for(int i=0;i<iTimes;i++) {

            final long messageId = System.currentTimeMillis();
            LogUtil.e("iTimes",i+"==");
            SiecomDevice.startInputPwd(bankCardNo, MasterKeyIndex, WasterKeyIndex, encryptType, length,passVioce, new DeviceCallback() {
                @Override
                public void onStart() {


                }

                @Override
                public void onError(Bundle bundle) {
                    int code = bundle.getInt("code");
                    String msg = bundle.getString("message");
                    if (code == ErrorDefine.CANCEL_INPUT) {

                    }
                    if (code == ErrorDefine.KEY_TIME_OUT) {

                    }
                    if (code == ErrorDefine.LENGTH_ERR) {

                    }

                    if (code != ErrorDefine.KEY_INPUT_ERR) {
                        ResultLock lock = LockMap.pick(messageId);

                        if (lock != null) {
                            synchronized (lock) {

                                lock.notify();
                                lock.setMessage(code+"");

                            }
                        }
                    }

                }

                @Override
                public void onSuccess(Bundle bundle) {
                    int num = bundle.getInt("data");
                    StringBuffer buf = new StringBuffer();
                    for (int i = 0; i < num; i++)
                        buf.append("*");


                }

                @Override
                public void onCompleted(Bundle bundle) {

                    ResultLock lock = LockMap.pick(messageId);
                    String pwd =  bundle.getString("data");

                    LogUtil.e("pwd","onCompleted:"+pwd);
                    if (lock != null) {

                        synchronized (lock) {

                            lock.notify();
                            lock.setMessage(pwd);

                        }

                    }

                }
            }, Integer.valueOf(strTimeout) * 1000,1, false);

            ResultLock r2 = new ResultLock(messageId);
            LockMap.store(messageId, r2);
            try {
                synchronized (r2) {
                    r2.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            } finally {
                LockMap.del(messageId);
            }
            passVioce = 1;
            if(i==0){
                lastPwd = (String) r2.getMessage();
                LogUtil.e("lastPwd",lastPwd);
                ret[0] = "0";
                if(lastPwd.length() < 8){
                    int lastInt = Integer.valueOf(lastPwd).intValue();
                    if(lastInt < 0){
                        ret[0] = lastPwd;
                        break;
                    }
                }
            }else {
                LogUtil.e("lastPwd:"+lastPwd,"r2:"+r2.getMessage());
                if(!lastPwd.equalsIgnoreCase((String) r2.getMessage())) {
                    i = i - 2;
                    passVioce = 2;
//                    String[] ret = new String[2];
//                    ret[0] = "-2";
//                    ret[1] = "input error";
//                    return ret;
                    continue;
                }
            }


        }


        ret[1] = lastPwd;
        return ret;
    }





    @Override
    public int SCCBA_InitPinPad() {

        setEncrypt();
        final long messageId = System.currentTimeMillis();

        SiecomDevice.resetKeyboard(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(-1);
                        lock.notify();

                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {

                LogUtil.e("GJ","初始化密钥成功");
                ResultLock lock = LockMap.pick(messageId);


                if (lock != null) {

                    synchronized (lock) {

                        lock.notify();
                        lock.setMessage(0);

                    }

                }
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, 15000, false);


        ResultLock r = new ResultLock(messageId);
        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(15000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }

        return (int) r.getMessage();
    }
    @Override
    public int SCCBA_UpdateMKey(int ZmkIndex, int ZmkLength, String Zmk, String CheckValue) {
        setEncrypt();
        final long messageId = System.currentTimeMillis();
//        String mkeyIndex = String.format("%02d", ZmkIndex);
        String mkeyIndex = "0x"+DecimalConVer(ZmkIndex);
        if(ZmkIndex < 10){
            mkeyIndex = "0"+DecimalConVer(ZmkIndex);
        }

        LogUtil.e("ZmkIndex", mkeyIndex);

        SiecomDevice.updateMainKey(mkeyIndex, Zmk.substring(0, ZmkLength), new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(-1);
                        lock.notify();

                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {
                String check = bundle.getString("data");

                ResultLock lock = LockMap.pick(messageId);

                LogUtil.e("GJ", check);

                if (lock != null) {

                    synchronized (lock) {

                        lock.notify();
                        lock.setMessage(0);

                    }

                }
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, 3000, false);


        ResultLock r = new ResultLock(messageId);
        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(3000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }

        return (int) r.getMessage();
    }

    public int setEncrypt() {
        int endType = 0;
        int mkeyIndex = 0;
        int wkeyIndex = 0;
        final long messageId = System.currentTimeMillis();
        SiecomDevice.keySetEncryptMode(ConstDefine.KEY_SM,endType,mkeyIndex,wkeyIndex, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");


//                Toast.makeText(DeviceActivity.this, "err:" + code + "--" + msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                ResultLock lock = LockMap.pick(messageId);

                LogUtil.e("GJ","设置加密模式成功");
                if (lock != null) {

                    synchronized (lock) {

                        lock.notify();
                        lock.setMessage(0);

                    }

                }
//                Toast.makeText(DeviceActivity.this, getResources().getString(R.string.set_encrypt), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, 3000, false);

        ResultLock r = new ResultLock(messageId);
        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(15000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        return (int) r.getMessage();

    }

    private String DecimalConVer(int pos){
        String data =  Integer.toHexString(pos);
        return data;
    }
    @Override
    public int SCCBA_DownLoadWKey(int MKeyIndex, int WKeyIndex, int WKeyLength, String Key, String CheckValue) {

        setEncrypt();

        final long messageId = System.currentTimeMillis();

//        String mkeyIndex = String.format("%02d", MKeyIndex);
        String mkeyIndex = "0x"+DecimalConVer(MKeyIndex);
        if(MKeyIndex < 10){
            mkeyIndex = "0"+DecimalConVer(MKeyIndex);
        }

        String wkeyIndex = "0x"+DecimalConVer(WKeyIndex);
        if(WKeyIndex < 10){
            wkeyIndex = "0"+DecimalConVer(WKeyIndex);
        }
//        String wkeyIndex = String.format("%02d", WKeyIndex);
//        String wkeyIndex = "0x"+DecimalConVer(WKeyIndex);
        LogUtil.e("GJ","主密钥工作密钥"+mkeyIndex+"------"+wkeyIndex);
        SiecomDevice.inputWorkKey(mkeyIndex, wkeyIndex, Key.substring(0, WKeyLength),encryptType,0x81, new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {


                        lock.setMessage(-1);
                        lock.notify();

                    }
                }


            }

            @Override
            public void onSuccess(Bundle bundle) {
                String check = bundle.getString("data");

                ResultLock lock = LockMap.pick(messageId);

                LogUtil.e("GJ", check);

                if (lock != null) {

                    synchronized (lock) {

                        lock.notify();
                        lock.setMessage(0);

                    }

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, 3000, false);


        ResultLock r = new ResultLock(messageId);
        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(3000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }

        return (int) r.getMessage();
    }

    @Override
    public int SCCBA_ActiveWKey(int MKeyIndex, int WKeyIndex) {

        if(MKeyIndex < 10){
            this.MasterKeyIndex = "0"+MKeyIndex;
        }else{
            this.MasterKeyIndex = ""+MKeyIndex;
        }
        if(WKeyIndex < 10){
            WasterKeyIndex = "0"+WKeyIndex;
        }else{
            WasterKeyIndex = ""+WKeyIndex;
        }

//        String[] ret = new String[2];
//        ret[0] = "0";

        return 0;
//        final long messageId = System.currentTimeMillis();
//        int encryptType = ConstDefine.KEY_SM;
//
//        SiecomDevice.keySetEncryptMode(encryptType, -1, MKeyIndex, WKeyIndex, new DeviceCallback() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onError(Bundle bundle) {
//                int code = bundle.getInt("code");
//                String msg = bundle.getString("message");
//                ResultLock lock = LockMap.pick(messageId);
//
//                if (lock != null) {
//                    synchronized (lock) {
//
//                        lock.notify();
//                        lock.setMessage(-1);
//                    }
//                }
//
//            }
//
//            @Override
//            public void onSuccess(Bundle bundle) {
//
//                ResultLock lock = LockMap.pick(messageId);
//
//                if (lock != null) {
//                    synchronized (lock) {
//
//                        lock.notify();
//                        lock.setMessage(0);
//                    }
//                }
//
//
//            }
//
//            @Override
//            public void onCompleted(Bundle bundle) {
//
//            }
//        }, 3000, false);
//        ResultLock r = new ResultLock(messageId);
//        LockMap.store(messageId, r);
//        try {
//            synchronized (r) {
//                r.wait(3000 + 3000);
//            }
//        } catch (Exception ee) {
//            ee.printStackTrace();
//        } finally {
//            LockMap.del(messageId);
//        }
//
//        return (int) r.getMessage();
    }
    @Override
    public String[] SCCBA_GetICCInfo(int ICType, String AIDList, final String TagList, String strTimeout) {

        final long messageId = System.currentTimeMillis();

        EmvOptions options = new EmvOptions();
        EMVParam emvParam = new EMVParam();
        byte[] MerchCateCode = new byte[2];
        MerchCateCode[0] = 0x00;
        MerchCateCode[1] = 0x01;
        emvParam.setMerchCateCode(MerchCateCode);
        String MerchId = "123456789012345";
        emvParam.setMerchId(MerchId.getBytes());
        emvParam.setMerchName("EMV LIBRARY".getBytes());
        emvParam.setTermId("12345678".getBytes());
        emvParam.setTerminalType((byte) 0x22);
        emvParam.setSurportPSESel((byte) 0x01);
        byte[] Capability = {(byte) 0xE0, (byte) 0x60, (byte) 0xC8};
        emvParam.setCapability(Capability);
        byte[] ExCapability = {(byte) 0x60, (byte) 0x00, (byte) 0xF0,
                (byte) 0x20, (byte) 0x01};
        emvParam.setExCapability(ExCapability);
        byte[] CountryCode = {(byte) 0x01, (byte) 0x56};
        byte[] TransCurrCode = {(byte) 0x01, (byte) 0x56};
        byte[] ReferCurrCode = {(byte) 0x01, (byte) 0x56};
        emvParam.setCountryCode(CountryCode);
        emvParam.setTransCurrCode(TransCurrCode);
        emvParam.setTransCurrExp((byte) 0x02);
        emvParam.setReferCurrCode(CountryCode);
        emvParam.setCL_TransLimit(100000);
        emvParam.setTransType((byte) 0x00);// 交易类型
        byte[] TermTransQuali = {0x24, 0x00, 0x00, (byte) 0x80};
        emvParam.setTermTransQuali(TermTransQuali);
        emvParam.setCL_bStatusCheck((byte) 0x00);
        emvParam.setCL_CVMLimit(10000);
        emvParam.setCL_FloorLimit(20000);

        emvParam.setECTSI((byte) 0x01);
        emvParam.setEC_TermLimit(10000);
        emvParam.setEC_bTermLimitCheck((byte) 0x01);

        options.setEmvParam(emvParam);
        options.setAuthorizedAmount(1);

        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
        String time = df.format(new Date());
        options.setTime(time);
        options.setTransNo(1);


//                String[] tags = {"5A", "57", "9F26", "9F27", "9F10", "9F37", "9F36",
//                        "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03",
//                        "9F33", "9F34", "9F35", "9F1E", "4F", "5F34"};

        //"9F61", "9F1F""5F24",9F78"9F42",
        String[] tags = {"5A", "57", "5F20", "9F62", "9F61", "9F1F", "9F79",
                "9F77", "5F24", "5F34",
                "9F34", "9F78", "9F42",
                "9F26", "9F27", "9F10", "9F37", "9F36",
                "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33"};

//        String[] tags = {"5A", "57", "5F20", "9F62", "9F79","9F77",
//                 "5F34", "9F26", "9F27", "9F10", "9F37", "9F36",
//                "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33",
//                "9F34"};

        int cardType = 0;
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            cardType = ConstDefine.AUTO_CARD;
        }

        SiecomDevice.readBankCard(cardType, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {
                StringBuffer sb = new StringBuffer();

                BankCardInfoBean bean = bundle.getParcelable("data");


                String userName = StringUtil.tagParse("5F20",
                        bean.ICChipData);
//                byte[] nameByte = ByteTool.hexStr2Bytes(userName);
//                try {
//                  userName = new String(nameByte, "gb2312")
//                            .trim();
//                    LogUtil.e("userName：",
//                            new String(nameByte, "gb2312").trim());
//                } catch (UnsupportedEncodingException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
                String credentialType = StringUtil.tagParse("9F62",
                        bean.ICChipData);

                LogUtil.e("credentialType：", credentialType);

                String documentNumber = StringUtil.tagParse("9F61",
                        bean.ICChipData);
                byte[] documentByte = ByteTool
                        .hexStr2Bytes(documentNumber);

                LogUtil.e("documentNumber：",
                        new String(documentByte).trim());
                int len5A = StringUtil.getTagLen(0, "5A",
                        bean.ICChipData);



                String track1Data = StringUtil.tagParse("9F1F",
                        bean.ICChipData);

                LogUtil.e("track1Data：", track1Data);

                // 余额
                String accountBalance = StringUtil.tagParse("9F79",
                        bean.ICChipData);

                LogUtil.e("accountBalance：", accountBalance);

                // 余额上限
                String balanceCap = StringUtil.tagParse("9F77",
                        bean.ICChipData);

                LogUtil.e("balanceCap：", balanceCap);

                // 失效日期
                String expDate = StringUtil.tagParse("5F24",
                        bean.ICChipData);

                LogUtil.e("expDate：", expDate);

                // 卡序列号
                String serialNumber = StringUtil.tagParse("5F34",
                        bean.ICChipData);

                LogUtil.e("serialNumber：", serialNumber);

                int pos = bean.ICChipData.indexOf("9F26");

                // 应用货币类型
                String moneyType = StringUtil.tagParse("9F42",
                        bean.ICChipData);

                //单笔限额
                String oneLimit = StringUtil.tagParse("9F78",
                        bean.ICChipData);


                bundle.putString("55field",
                        bean.ICChipData.substring(pos));
                LogUtil.e("ret","五五域"+bean.ICChipData.substring(pos));

                if (TagList.indexOf("A") != -1) {
                    String str = String.format("%03d", bean.cardNo.length());
                    sb.append("A" + str);
                    sb.append(bean.cardNo);
                }
                if (TagList.indexOf("B") != -1) {
                    String str = String.format("%03d", userName.length());
                    sb.append("B" + str);
                    sb.append(userName);
                }
                if (TagList.indexOf("C") != -1) {
                    String str = String.format("%03d", credentialType.length());
                    sb.append("C" + str);
                    sb.append(credentialType);
                }
                if (TagList.indexOf("D") != -1) {
                    String str = String.format("%03d", documentNumber.length());
                    sb.append("D" + str);
                    sb.append(documentNumber);
                }
                if (TagList.indexOf("E") != -1) {
                    String str = String.format("%03d", accountBalance.length());
                    sb.append("E" + str);
                    sb.append(accountBalance);
                }
                if (TagList.indexOf("F") != -1) {
                    String str = String.format("%03d", balanceCap.length());
                    sb.append("F" + str);
                    sb.append(balanceCap);
                }
                if (TagList.indexOf("G") != -1) {
                    String str = String.format("%03d", oneLimit.length());
                    sb.append("G" + str);
                    sb.append(oneLimit);
                }
                if (TagList.indexOf("H") != -1) {
                    String str = String.format("%03d", moneyType.length());
                    sb.append("H" + str);
                    sb.append(moneyType);
                }
                if (TagList.indexOf("I") != -1) {
                    String str = String.format("%03d", expDate.length());
                    sb.append("I" + str);
                    sb.append(expDate);
                }

                if (TagList.indexOf("J") != -1) {
                    String str = String.format("%03d", serialNumber.length());
                    sb.append("J" + str);
                    sb.append(serialNumber);
                }
                if (TagList.indexOf("K") != -1) {
                    String str = String.format("%03d", bean.twoMagneticTrack.length());
                    sb.append("K" + str);
                    sb.append(bean.twoMagneticTrack);
                }
                if (TagList.indexOf("L") != -1) {
                    String str = String.format("%03d", track1Data.length());
                    sb.append("L" + str);
                    sb.append(track1Data);
                }


                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[4];
                        ret[0] = "0";
                        ret[1] = sb.toString();
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, options, tags, Integer.valueOf(strTimeout) * 1000, false);


        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(10000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }

        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }
    @Override
    public String[] SCCBA_GetARQC(int ICType, String txDataString, String AIDList, String strTimeout) {

        int nIndex = txDataString.indexOf('P');
        int authAmount = 0, backAmount = 0;
        byte[] CountryCode = {(byte) 0x01, (byte) 0x56};
        byte[] TransCurrCode = {(byte) 0x01, (byte) 0x56};
        byte[] ReferCurrCode = {(byte) 0x01, (byte) 0x56};
        byte[] TransCurrType = new byte[1];
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
        String time = df.format(new Date());
        String dateString = time;

        if (nIndex != -1) {
            String substr = txDataString.substring(nIndex + 1,
                    nIndex + 4);
            int lens = Integer.parseInt(substr);
            String authAmountString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);
            if ((lens % 2) != 0)
                authAmountString = "0" + authAmountString;
//			byte[] authAmount = StringUtil.hexStringToBytes(authAmountString);
            authAmount = Integer.parseInt(authAmountString);

        }

        nIndex = txDataString.indexOf('Q');
        if (nIndex != -1) {
            String substr = txDataString.substring(nIndex + 1,
                    nIndex + 4);
            int lens = Integer.parseInt(substr);
            String backAmountString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);
            if ((lens % 2) != 0)
                backAmountString = "0" + backAmountString;
//			byte[] authAmount = StringUtil.hexStringToBytes(authAmountString);
            backAmount = Integer.parseInt(backAmountString);

        }

        nIndex = txDataString.indexOf('R');
        if (nIndex != -1) {
            String substr = txDataString.substring(nIndex + 1,
                    nIndex + 4);
            int lens = Integer.parseInt(substr);
            String TransCurrCodeString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);
            if ((lens % 2) != 0) {
                TransCurrCodeString = "0" + TransCurrCodeString;
            }
            TransCurrCode = ByteTool.hexStr2Bytes(TransCurrCodeString);

        }
//		P012000000000000   授权金额
//		Q012000000000000其它金额
//		R003156交易货币代码
//		S00820150724交易日期
//		T00217交易类型
//		U006133523交易时间
//		V000
        nIndex = txDataString.indexOf('S');
        if (nIndex != -1) {
            String substr = txDataString.substring(nIndex + 1,
                    nIndex + 4);
            int lens = Integer.parseInt(substr);

            dateString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);

            if ((lens % 2) != 0)
                dateString = "0" + dateString;
//			StringUtil.hexStringToBytes(dateString);

            nIndex = txDataString.indexOf('U');
            if (nIndex != -1) {
                substr = txDataString.substring(nIndex + 1,
                        nIndex + 4);
                lens = Integer.parseInt(substr);
                String dayString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);
                if ((lens % 2) != 0)
                    dayString = "0" + dayString;


                dateString += dayString;
            }
        }
        nIndex = txDataString.indexOf('T');
        if (nIndex != -1) {
            String substr = txDataString.substring(nIndex + 1,
                    nIndex + 4);
            int lens = Integer.parseInt(substr);
            String TransTypeString = txDataString.substring(nIndex + 4, nIndex + 4 + lens);
            if ((lens % 2) != 0) {
                TransTypeString = "0" + TransTypeString;
            }
            TransCurrType = ByteTool.hexStr2Bytes(TransTypeString);

        }

        final long messageId = System.currentTimeMillis();
        int cardType = 0;
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            cardType = ConstDefine.AUTO_CARD;
        }
        EmvOptions options = new EmvOptions();
        EMVParam emvParam = new EMVParam();
        byte[] MerchCateCode = new byte[2];
        MerchCateCode[0] = 0x00;
        MerchCateCode[1] = 0x01;
        emvParam.setMerchCateCode(MerchCateCode);
        String MerchId = "123456789012345";
        emvParam.setMerchId(MerchId.getBytes());
        emvParam.setMerchName("EMV LIBRARY".getBytes());
        emvParam.setTermId("12345678".getBytes());
        emvParam.setTerminalType((byte) 0x22);
        emvParam.setSurportPSESel((byte) 0x01);

        byte[] Capability = {(byte) 0xE0, (byte) 0x60, (byte) 0xC8};
        emvParam.setCapability(Capability);
        byte[] ExCapability = {(byte) 0x60, (byte) 0x00, (byte) 0xF0,
                (byte) 0x20, (byte) 0x01};
        emvParam.setExCapability(ExCapability);

        emvParam.setCountryCode(CountryCode);

        emvParam.setTransCurrExp((byte) 0x02);
        emvParam.setReferCurrCode(CountryCode);
        emvParam.setCL_TransLimit(100000);

        byte[] TermTransQuali = {0x24, 0x00, 0x00, (byte) 0x80};
        emvParam.setTermTransQuali(TermTransQuali);
        emvParam.setCL_bStatusCheck((byte) 0x00);
        emvParam.setCL_CVMLimit(10000);
        emvParam.setCL_FloorLimit(20000);

        emvParam.setECTSI((byte) 0x01);
        emvParam.setEC_TermLimit(10000);
        emvParam.setEC_bTermLimitCheck((byte) 0x01);

        options.setEmvParam(emvParam);
        options.setAuthorizedAmount(1);
        options.setBackAmount(backAmount);
        emvParam.setTransType(TransCurrType[0]);// 交易类型
        emvParam.setTransCurrCode(TransCurrCode);

        options.setTime(dateString.substring(2));
        options.setTransNo(1);

        String[] tags = new String[]{"5A", "57", "9F34", "9F35", "9F1E", "4F", "5F34",
                "9F26", "9F27", "9F10", "9F37", "9F36",
                "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03",
                "9F33"};

//        "9F26", "9F27", "9F10", "9F37", "9F36",
//                "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33"};
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            cardType = ConstDefine.AUTO_CARD;
        }

        SiecomDevice.readBankCard(cardType, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {


                BankCardInfoBean bean = bundle.getParcelable("data");

                int pos = bean.ICChipData.indexOf("9F26");
                bean.ICChipData = bean.ICChipData.substring(pos);
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[4];
                        ret[0] = "0";
                        ret[1] = bean.ICChipData;
                        ret[2] = bean.ICChipData;
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, options, tags, Integer.valueOf(strTimeout) * 1000, false);


        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(10000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }

        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();

    }

    @Override
    public String[] SCCBA_GetICAndARQCInfo(int ICType, String AIDList,String TagList, String TxData, String strTimeout) {
        String[] ret = new String[4];
        String[] ICCInfo = SCCBA_GetICCInfo(ICType,AIDList,TagList,strTimeout);
        ret[0] = ICCInfo[0];
        ret[1] = ICCInfo[1];
        String[] GetARQC = SCCBA_GetARQC(ICType,TxData,AIDList,strTimeout);
        ret[0] = GetARQC[0];
        ret[2] = GetARQC[1];
        ret[3] = GetARQC[2];

        return ret;
    }

    @Override
    public String[] SCCBA_ARPCExeScript(int ICType, String Txdata, String ARPC, String CDol2) {

        //Txdata 和 CDol2 并没有什么卵用
        LogUtil.e("Txdata", Txdata);
        LogUtil.e("CDol2", CDol2);

        final long messageId = System.currentTimeMillis();

        int cardType = 0;
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            String[] ret = new String[2];
            ret[0] = "-1";
            ret[1] = "no support";

            return ret;
        }

        SiecomDevice.ARPCExecuteScript(cardType, ARPC, ARPC, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {


                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }
            }

            @Override
            public void onSuccess(Bundle bundle) {

                String ScriptResult = bundle.getString("ScriptResult");
                String TC = bundle.getString("TC");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[4];
                        String str = String.format("%02d", TC.length());
                        ret[0] = "0";
                        ret[1] = "DF31" + str + TC;
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }


            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        }, 10000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(10000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }

        return (String[]) r.getMessage();

    }
    @Override
    public String[] SCCBA_GetTrDetail(int ICType, final int NOLog, String strTimeout) {

        final long messageId = System.currentTimeMillis();
        int cardType = 0;
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            cardType = ConstDefine.AUTO_CARD;
        }

        SiecomDevice.readTradeLog(cardType, new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {
                List<TradeLogBean> list = bundle.getParcelableArrayList("data");
                LogUtil.e("TradeLogBean","--"+list.size());
                ResultLock lock = LockMap.pick(messageId);
                StringBuffer buff = new StringBuffer();

                if (NOLog == 0) {
                    for (TradeLogBean bean : list) {

                        LogUtil.e("logbean:", bean.getMerchName());
                        buff.append("P012");
                        buff.append(bean.getAmount());
                        buff.append("Q012");
                        buff.append(bean.getOtherAmount());
                        buff.append("R004");
                        buff.append(bean.getTransCurrCode());
                        buff.append("S006");
                        buff.append(bean.getDate());
                        buff.append("T002");
                        buff.append(bean.getTransType());
                        buff.append("U006");
                        buff.append(bean.getTime());
                        buff.append("V004");
                        buff.append(bean.getCountryCode());

                        String str = String.format("%03d", bean.getMerchName().length());
                        buff.append("W" + str);
                        buff.append(bean.getMerchName());
                        str = String.format("%03d", String.valueOf(bean.getTransNo()).length());
                        buff.append("X" + str);
                        buff.append(bean.getTransNo());
                    }
                } else {

                    TradeLogBean bean = list.get(NOLog);
                    buff.append("P012");
                    buff.append(bean.getAmount());
                    buff.append("Q012");
                    buff.append(bean.getOtherAmount());
                    buff.append("R004");
                    buff.append(bean.getTransCurrCode());
                    buff.append("S006");
                    buff.append(bean.getDate());
                    buff.append("T002");
                    buff.append(bean.getTransType());
                    buff.append("U006");
                    buff.append(bean.getTime());
                    buff.append("V004");
                    buff.append(bean.getCountryCode());

                    String str = String.format("%03d", bean.getMerchName().length());
                    buff.append("W" + str);
                    buff.append(bean.getMerchName());
                    str = String.format("%03d", String.valueOf(bean.getTransNo()).length());
                    buff.append("X" + str);
                    buff.append(bean.getTransNo());

                }


                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = "0";
                        ret[1] = buff.toString();
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        }, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();

    }
    @Override
    public String[] SCCBA_GetLoadLog(int ICType, final int NOLog, String AIDList, String strTimeout) {

        final long messageId = System.currentTimeMillis();
        int cardType = 0;
        if (ICType == 0) {
            cardType = ConstDefine.IC_CARD;
        }
        if (ICType == 1) {
            cardType = ConstDefine.PIC_CARD;
        }
        if (ICType == 2) {
            cardType = ConstDefine.AUTO_CARD;
        }

        SiecomDevice.readLoadLog(cardType, new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {
                List<LoadLogBean> list = bundle.getParcelableArrayList("data");

                ResultLock lock = LockMap.pick(messageId);
                StringBuffer buff = new StringBuffer();
                int i = 0;
                for (LoadLogBean bean : list) {
                    if (i == NOLog) {
                        break;
                    }
                    LogUtil.e("logbean:", bean.getMerchName());
                    buff.append("P012");
                    buff.append(bean.getBeforeAmount());
                    buff.append("Q012");
                    buff.append(bean.getAfterAmount());
                    buff.append("R004");
                    buff.append(bean.getTransCurrCode());
                    buff.append("S006");
                    buff.append(bean.getDate());
                    buff.append("T002");
                    buff.append(bean.getTransType());
                    buff.append("U006");
                    buff.append(bean.getTime());
                    buff.append("V004");
                    buff.append(bean.getCountryCode());

                    String str = String.format("%03d", bean.getMerchName().length());
                    buff.append("W" + str);
                    buff.append(bean.getMerchName());
                    str = String.format("%03d", String.valueOf(bean.getTransNo()).length());
                    buff.append("X" + str);
                    buff.append(bean.getTransNo());

                    i++;

                }


                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = "0";
                        ret[1] = buff.toString();
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onCompleted(Bundle bundle) {


            }
        }, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();

    }

    @Override
    public String[] SCCBA_MsfRead(String readModel, String strTimeout) {

        final long messageId = System.currentTimeMillis();


        EmvOptions options = new EmvOptions();
        EMVParam emvParam = new EMVParam();
        byte[] MerchCateCode = new byte[2];
        MerchCateCode[0] = 0x00;
        MerchCateCode[1] = 0x01;
        emvParam.setMerchCateCode(MerchCateCode);
        String MerchId = "123456789012345";
        emvParam.setMerchId(MerchId.getBytes());
        emvParam.setMerchName("EMV LIBRARY".getBytes());
        emvParam.setTermId("12345678".getBytes());
        emvParam.setTerminalType((byte) 0x22);
        emvParam.setSurportPSESel((byte) 0x01);
        byte[] Capability = {(byte) 0xE0, (byte) 0x60, (byte) 0xC8};
        emvParam.setCapability(Capability);
        byte[] ExCapability = {(byte) 0x60, (byte) 0x00, (byte) 0xF0,
                (byte) 0x20, (byte) 0x01};
        emvParam.setExCapability(ExCapability);
        byte[] CountryCode = {(byte) 0x01, (byte) 0x56};
        byte[] TransCurrCode = {(byte) 0x01, (byte) 0x56};
        byte[] ReferCurrCode = {(byte) 0x01, (byte) 0x56};
        emvParam.setCountryCode(CountryCode);
        emvParam.setTransCurrCode(TransCurrCode);
        emvParam.setTransCurrExp((byte) 0x02);
        emvParam.setReferCurrCode(CountryCode);
        emvParam.setCL_TransLimit(100000);
        emvParam.setTransType((byte) 0x00);// 交易类型
        byte[] TermTransQuali = {0x24, 0x00, 0x00, (byte) 0x80};
        emvParam.setTermTransQuali(TermTransQuali);
        emvParam.setCL_bStatusCheck((byte) 0x00);
        emvParam.setCL_CVMLimit(10000);
        emvParam.setCL_FloorLimit(20000);

        emvParam.setECTSI((byte) 0x01);
        emvParam.setEC_TermLimit(10000);
        emvParam.setEC_bTermLimitCheck((byte) 0x01);

        options.setEmvParam(emvParam);
        options.setAuthorizedAmount(1);

        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
        String time = df.format(new Date());
        options.setTime(time);
        options.setTransNo(1);

        String[] tags = {"5A", "57", "5F20", "9F62", "9F61", "9F1F", "9F79",
                "9F77", "5F24", "5F34",
                "9F34", "9F78", "9F42",
                "9F26", "9F27", "9F10", "9F37", "9F36",
                "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33"};

        SiecomDevice.readBankCard(ConstDefine.MSR_CARD, new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }


            }

            @Override
            public void onSuccess(Bundle bundle) {

                final BankCardInfoBean bean = bundle.getParcelable("data");

                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[4];
                        ret[0] = "0";
                        ret[1] = bean.twoMagneticTrack + "<" + bean.threeMagneticTrack;
                        ret[2] = bean.twoMagneticTrack;
                        ret[3] = bean.threeMagneticTrack;
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }

        }, options, tags, Integer.valueOf(strTimeout) * 1000, false);


        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }

    @Override
    public String[] SCCBA_MsfWrite(String s, String s1, String s2) {

        String[] ret = new String[2];
        ret[0] = "-1";
        ret[1] = "no support";
        return ret;
    }

//    public static String[] SCCBA_MsfWrite(String sTrack2, String sTrack3, String strTimeout) {
//        String[] ret = new String[2];
//        ret[0] = "-1";
//        ret[1] = "no support";
//        return ret;
//    }

    //    @Override
//    public String[] SCCBA_ReadFinger(String s, String s1, String s2) {
//
//        String[] ret = new String[2];
//        ret[0] = "-1";
//        ret[1] = "no support";
//        return ret;
//    }
    @Override
    public String[] SCCBA_ReadFinger(final String fingerImgPath ,String fingerType, String strTimeout) {

        final long messageId = System.currentTimeMillis();

        SiecomDevice.readFingerPic(new DeviceCallback() {
            @Override
            public void onStart() {


            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {

                Bitmap bm = bundle.getParcelable("Img");
                String feature = bundle.getString("data");

                ResultLock lock = LockMap.pick(messageId);
                saveBitmapTofile(bm,fingerImgPath);

                if (lock != null) {

                    synchronized (lock) {
                        String bmp = Base64.encodeToString(FileUnits.Bitmap2Bytes(bm), 0);
                        String[] ret = new String[5];
                        ret[0] = "0";
                        ret[1] = fingerImgPath;
                        ret[2] = String.valueOf(bmp.length());
                        ret[3] = feature;
                        ret[4] = String.valueOf(feature.length());
                        lock.notify();
                        lock.setMessage(ret);

                    }

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, Integer.valueOf(strTimeout) * 1000, false);


        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }
    private boolean saveBitmapTofile(Bitmap bmp, String filename) {
        if (bmp == null || filename == null)
            return false;
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return bmp.compress(format, quality, stream);
    }

    @Override
    public String[] SCCBA_ReadIDFullInfo(final String strPhotoPath, String strTimeout) {

        final long messageId = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Bundle bundle) {

                IdentityInfoBean bean = bundle.getParcelable("data");
                ResultLock lock = LockMap.pick(messageId);

                FileUnits.saveImage(bean.getIcon(), strPhotoPath);

                if (lock != null) {

                    synchronized (lock) {
                        String[] ret = new String[9];
                        ret[0] = "0";
                        ret[1] = bean.getFullName();
                        ret[2] = bean.getSex();
                        ret[3] = bean.getNation();
                        ret[4] = bean.getBirthday();
                        ret[5] = bean.getIdAddr();
                        ret[6] = bean.getIdNo();
                        ret[7] = bean.getIdOrg();
                        ret[8] = bean.getBeginDate() + "-" + bean.getEndDate();

                        lock.notify();
                        lock.setMessage(ret);

                    }

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {


            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }
            }
        };
        SiecomDevice.readIdentityCard(taskCallback, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }

    @Override
    public String[] SCCBA_ReadIDAndAPRPInfo(final String strPhotoPath, final String strTimeout) {

        final long messageId = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Bundle bundle) {

                IdentityInfoBean bean = bundle.getParcelable("data");
                ResultLock lock = LockMap.pick(messageId);

                FileUnits.saveImage(bean.getIcon(), strPhotoPath);

                if (lock != null) {

                    synchronized (lock) {
                        String[] ret = new String[12];

                        if(bean.getCardType().equals("I")){
                            ret[0] = "I";
                            ret[1] = bean.getEnName();
                            ret[2] = bean.getSex();
                            ret[3] = bean.getNation();
                            ret[4] = bean.getCountryCode();
                            ret[5] = bean.getFullName();
                            ret[6] = bean.getBeginDate();
                            ret[7] = bean.getEndDate();
                            ret[8] = bean.getBirthday();
                            ret[9] = bean.getCardVer();
                            ret[10] = bean.getIdOrg();
                            ret[11] = bean.getCardType();
                        }else{
                            ret[0] = "C";
                            ret[1] = bean.getFullName();
                            ret[2] = bean.getSex();
                            ret[3] = bean.getNation();
                            ret[4] = bean.getBirthday();
                            ret[5] = bean.getIdAddr();
                            ret[6] = bean.getIdNo();
                            ret[7] = bean.getIdOrg();
                            ret[8] = bean.getBeginDate() + "-" + bean.getEndDate();
                        }


//                        ret[1] = bean.getFullName();
//                        ret[2] = bean.getSex();
//                        ret[3] = bean.getNation();
//                        ret[4] = bean.getBirthday();
//                        ret[5] = bean.getIdAddr();
//                        ret[6] = bean.getIdNo();
//                        ret[7] = bean.getIdOrg();
//                        ret[8] = bean.getBeginDate() + "-" + bean.getEndDate();

                        lock.notify();
                        lock.setMessage(ret);

                    }

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {


            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }
            }
        };
        SiecomDevice.readIdentityCard(taskCallback, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }

    @Override
    public String[] SCCBA_ReadAPRPInfo(final String strPhotoPath, String strTimeout) {

        final long messageId = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Bundle bundle) {

                IdentityInfoBean bean = bundle.getParcelable("data");
                ResultLock lock = LockMap.pick(messageId);

                FileUnits.saveImage(bean.getIcon(), strPhotoPath);

                if (lock != null) {

                    synchronized (lock) {
                        String[] ret = new String[12];
                        ret[0] = "0";
                        ret[1] = bean.getEnName();
                        ret[2] = bean.getSex();
                        ret[3] = bean.getNation();
                        ret[4] = bean.getCountryCode();
                        ret[5] = bean.getFullName();
                        ret[6] = bean.getBeginDate();
                        ret[7] = bean.getEndDate();
                        ret[8] = bean.getBirthday();
                        ret[9] = bean.getCardVer();
                        ret[10] = bean.getIdOrg();
                        ret[11] = bean.getCardType();


                        lock.notify();
                        lock.setMessage(ret);

                    }

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {


            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }
            }
        };
        SiecomDevice.readIdentityCard(taskCallback, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }

    @Override
    public String[] SCCBA_getSignature(final String strSignPath, String strTimeout) {

        final long messageId = System.currentTimeMillis();

        DeviceCallback taskCallback = new DeviceCallback() {


            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = String.valueOf(code);
                        ret[1] = String.valueOf(msg);
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {

                Bitmap signature = bundle.getParcelable("data");

                ResultLock lock = LockMap.pick(messageId);

                FileUnits.saveImage(signature, strSignPath+"1.png");

                if (lock != null) {

                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = "0";
                        ret[1] = strSignPath+"1.png";
                        lock.notify();
                        lock.setMessage(ret);

                    }

                }

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        };

        SiecomDevice.getSignature(taskCallback, Integer.valueOf(strTimeout) * 1000, false);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(strTimeout) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }
        return (String[]) r.getMessage();
    }

    @Override
    public String[] SCCBA_cancel() {

        final long messageId = System.currentTimeMillis();

        SiecomDevice.cancelCurrentTask(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {
                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = "-1";
                        ret[1] = "取消任务失败，请重试...";
                        lock.notify();
                        lock.setMessage(ret);
                    }
                }

            }

            @Override
            public void onSuccess(Bundle bundle) {

                Bitmap signature = bundle.getParcelable("data");

                ResultLock lock = LockMap.pick(messageId);

                if (lock != null) {

                    synchronized (lock) {
                        String[] ret = new String[2];
                        ret[0] = "0";
                        lock.notify();
                        lock.setMessage(ret);

                    }

                }
//                Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, 2000, true);

        ResultLock r = new ResultLock(messageId);

        LockMap.store(messageId, r);
        try {
            synchronized (r) {
                r.wait(Integer.valueOf(1) * 1000 + 3000);
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        } finally {
            LockMap.del(messageId);
        }
        if(r.getMessage()==null){
            String[] rs = new String[1];
            rs[0] = "-101";
            return rs;
        }

        return (String[]) r.getMessage();

    }


}
